package com.li.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 日志处理
 * @Aspect:可以进行切面的操作
 */
@Aspect
@Component
public class LogAspect {

    private final Logger logger= LoggerFactory.getLogger(this.getClass());

    /**
     * 切入点
     * @Pointcut:说明log()是切面（切入点）
     * execution 第一个参数是返回类型，第二个是web包下所有类的所有方法，..是任何参数
     */
    @Pointcut("execution(* com.li.web.*.*(..))")
    public void log(){

    }

    /**
     * 该方法会在切入点之前执行
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String url=request.getRequestURL().toString();
        String ip=request.getRemoteAddr();
        //joinPoint.getSignature().getDeclaringTypeName():类名
        //joinPoint.getSignature().getName()：方法名
        String classMethod=joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()+"()";
        Object []args=joinPoint.getArgs();
        RequestLog requestLog=new RequestLog(url,ip,classMethod,args);
        logger.info("方法信息 : {}",requestLog);
    }

    /**
     * 该方法会在切入点之后执行
     */
    @After("log()")
    public void doAfter(){
        //暂时不需要
        //logger.info("--------doAfter---------");
    }

    /**
     * 捕获方法返回的内容
     * @param result
     */
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterRuturn(Object result){
        logger.info("返回的内容 : {}",result);
    }

    private class RequestLog {
        private String url; //路径
        private String ip;  //ip
        private String classMethod; //方法名
        private Object[] args;  //请求的参数

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
